const fs = require('fs')


/**
 * 回调的方式 获取三个文件的内容
 * @return {[type]} [description]
 */
function callbackMethod() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0;
	var content = ''
	fs.readFile(files[i++], 'utf-8', function(err, data1) {
		content += data1;
		fs.readFile(files[i++], 'utf-8', function(err, data2) {
			content += data2;
			fs.readFile(files[i++], 'utf-8', function(err, data3) {
				content += data3;
				console.log(`content = ${content}, i = ${i}`)
			})
		})
	})
}

/**
 * 将一个错误优先(error-first)的回调函数 变为promise版本
 * @param  {Function} fn [description]
 * @return {[type]}      [description]
 */
function promisify(fn) {
	return function(...args) {
		return new Promise((resolve, reject) => {
			fn(...args, (err, data) => {
				if(err) {
					reject(err)
				} else {
					resolve(data)
				}
			})
		})		
	}
}


function callbackPromiseV1() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile = promisify(fs.readFile)

	readFile(files[i++], 'utf-8')
	.then(data => {
		content += data 
		return readFile(files[i++], 'utf-8')
	}).then(data => {
		content += data 
		return readFile(files[i++], 'utf-8')
	}).then(data => {
		content += data 
		console.log(`data = ${data}, i = ${i}`)
		console.log('-----------------------\n')
		console.log(content)
	})
}

 




// 【V2 失败的版本】 不能用循环，因为promise的then方法是异步的
// 循环的方式不好控制，适合用递归进行迭代
function callbackPromiseV2() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile = promisify(fs.readFile)

	function buildContent (data, idx) {
		content += data 
		return readFile(files[idx], 'utf-8')
	}

	
	var p = readFile(files[i], 'utf-8'); // 获取到promise对象进行链式调用
	// 最后一次是获取最终结果, 不能遍历到最后一次
	while(i++ < files.length-1) {
		p = p.then(data => {console.log( i)})
	}

	// p.then(data => {
	// 	content += data 
	// 	console.log(`data = ${data}, i = ${i}`)
	// 	console.log('-----------------------\n')
	// 	console.log(content)
	// })
}

function callbackPromiseV3() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile = promisify(fs.readFile)

	function buildContent (data, idx) {
		content += data 
		return readFile(files[idx], 'utf-8')
	}

	function co(promise, i, onFinished) {
		++i;
		if(i >= files.length) {
			// 这里还是同步 快于异步， 递归只是保证了i 正确传递了
			console.log('sdfsdf', content, i)
			
			onFinished(content)
			return 
		}
		var p = promise.then(data => {
			content += data 
			return readFile(files[i], 'utf-8')
		})
		co(p, i, onFinished)
	}
	var p = readFile(files[i], 'utf-8'); // 获取到promise对象进行链式调用
	co(p, i, function onFinished (content) {
		console.log('执行完后的内容: ', content)
	})

	// p.then(data => {
	// 	content += data 
	// 	console.log(`data = ${data}, i = ${i}`)
	// 	console.log('-----------------------\n')
	// 	console.log(content)
	// })
}



function callbackPromiseV4() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile = promisify(fs.readFile)

	function buildContent (data, idx) {
		content += data 
		return readFile(files[idx], 'utf-8')
	}

	function co(promise, i, onFinished) {
		++i;
		if(i >= files.length) {
			return promise
		}
		var p = promise.then(data => {
			content += data 
			return readFile(files[i], 'utf-8')
		})
		return co(p, i, onFinished)
	}
	var p = readFile(files[i], 'utf-8'); // 获取到promise对象进行链式调用
	co(p, i).then(data => {
		console.log('最后一次的链式调用:', data)
		console.log('-----------------------')
		console.log(content)
	})
}



/**
 *
	let readFile = promisify(fs.readFile);
	readFile('./name.txt', 'utf-8')
		.then(res => readFile(res, 'utf-8'))
		.then(res => readFile(res, 'utf-8'))
		.then(res => console.log(res))
 *
 */
function callbackPromiseV5() {
	var files = ['./resource/1.html','./resource/2.html','./resource/3.html']
	var i = 0, content = '';
	var readFile = promisify(fs.readFile)

	// 内部包装了2个函数
	function buildContent (data, idx) {
		content += data 
		return readFile(files[idx], 'utf-8')
	}

	function co(promise, i, onFinished) {
		// 进入函数之后 先 ++i
		if(++i >= files.length) {
			return promise
		}
		// 将相同的代码再抽取一次， buildContent 每次都是返回一个promise
		var p = promise.then(data => buildContent(data, i))
		return co(p, i, onFinished)
	}

	var p = readFile(files[i], 'utf-8'); // 获取到promise对象进行链式调用
	co(p, i).then(data => {
		console.log('最后一次的链式调用:', data)
		console.log('-----------------------')
		console.log(content)
	})
}
callbackPromiseV5()